package com.jike.noobmoney.mvp.view.activity;

import android.Manifest;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.image.imagepicker.ImagePicker;
import com.image.imagepicker.bean.ImageItem;
import com.image.imagepicker.ui.ImageGridActivity;
import com.jike.noobmoney.R;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.SmsEntity;
import com.jike.noobmoney.entity.UserInfoEntity;
import com.jike.noobmoney.helper.ImageLoader;
import com.jike.noobmoney.mvp.presenter.AppPresenter;
import com.jike.noobmoney.mvp.presenter.UserPresenter;
import com.jike.noobmoney.mvp.view.widget.BottomDialog;
import com.jike.noobmoney.net.IView;
import com.jike.noobmoney.net.RetrofitHelper;
import com.jike.noobmoney.rxbus.RxBus;
import com.jike.noobmoney.rxbus.RxBusRoute;
import com.jike.noobmoney.rxbus.RxEvent;
import com.jike.noobmoney.util.PerfectClickListener;
import com.jike.noobmoney.util.RegexUtils;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Create by xuke on 2018/11/10
 * 我的资料 (未完成)
 */
public class MyInfoActivityUpdate extends BaseActivity implements IView {

    private static final int REQUEST_CODE_SELECT = 111;

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.rl_avatar)
    RelativeLayout rlAvatar;
    @BindView(R.id.tv_nick)
    EditText tvNick;
    @BindView(R.id.tv_mobile)
    EditText tvMobile;
    @BindView(R.id.tv_user_info)
    TextView tvUserInfo;
    @BindView(R.id.tv_show_id)
    TextView tv_show_id;

    @BindView(R.id.btn_check_code)
    Button btnCheckCode;

    private boolean timeEnable = true;

    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.iidcard)
    EditText iidcard;

    @BindView(R.id.et_code)
    EditText et_code;

    @BindView(R.id.alipayaccount)
    EditText alipayaccount;

    private String userid;
    private Call<UserInfoEntity> userInfoCall;

    private AppPresenter appPresenter;
    private UserPresenter userPresenter;
    private String url;

    @Override
    protected int layoutResID() {
        return R.layout.activity_my_info_update;
    }

    @Override
    protected void initData() {
        tvTitle.setText("我的资料");
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);

        appPresenter = new AppPresenter(this);
        userPresenter = new UserPresenter(this);
        btnCheckCode.setOnClickListener(listener);
        getData();
    }
    /**
     * 如果要全屏,重写这个方法返回false
     */
    public Boolean isfits() {
        return true;
    }

    /**
     * 如果要白色主题,重写这个方法返回false
     */
    public boolean ismain() {
        return true;
    }
    /**
     * 获取个人信息
     */
    private void getData() {
        userInfoCall = RetrofitHelper.getInstance().getUserInfo(userid);
        userInfoCall.enqueue(new Callback<UserInfoEntity>() {
            @Override
            public void onResponse(Call<UserInfoEntity> call, Response<UserInfoEntity> response) {
                if (response != null) {
                    UserInfoEntity body = response.body();
                    if (body != null && "100".equals(body.getCode())) {
                        UserInfoEntity.UserBean user = body.getUser();
                        if (user != null) {
                            initView(user);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<UserInfoEntity> call, Throwable t) {
                ToastUtils.showShortToastSafe(t.getMessage());
            }
        });
    }

    private PerfectClickListener listener = new PerfectClickListener() {
        @Override
        protected void onNoDoubleClick(View v) {
            int id = v.getId();
            if (id == R.id.btn_check_code) {
                if (isVerPhone()) {
                    timeEnable = false;
                    btnCheckCode.setEnabled(false);
                    CountDownTimer mCountDownTimer = new CountDownTimer(
                            60 * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            long s = millisUntilFinished / 1000;
                            String text = s + "s";
                            btnCheckCode.setText(text);
                        }

                        @Override
                        public void onFinish() {
                            timeEnable = true;
                            btnCheckCode.setText("发送验证码");
                            boolean enable = !TextUtils.isEmpty(tvMobile.getText().toString());
                            btnCheckCode.setEnabled(enable);
                            this.cancel();
                        }
                    };
                    mCountDownTimer.start();
                    //发短信
                    getMessage();
                }
            } else if (id == R.id.tv_register) {

            }
        }

    };

    /**
     * 发送短信验证码
     */
    private void getMessage() {
        Call<SmsEntity> codeCall = RetrofitHelper.getInstance().getCode(tvMobile.getText().toString().trim());
        codeCall.enqueue(new Callback<SmsEntity>() {
            @Override
            public void onResponse(Call<SmsEntity> call, Response<SmsEntity> response) {
                if (response != null) {
                    SmsEntity body = response.body();
                    if (body != null) {
                        if ("100".equals(body.getCode())) {
                            //成功
//                            ToastUtils.showShortToastSafe(body.getRinfo());
//                            smscode = body.getSmscode();
//                            Log.e("xuke", "smsCode=" + smscode);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<SmsEntity> call, Throwable t) {
                Log.e("xuke", t.getMessage());
            }
        });

    }

    //检查手机号
    private boolean isVerPhone() {
        if (!RegexUtils.checkMobileNumber(tvMobile.getText().toString())) {
            ToastUtils.showShortToastSafe("请检查手机号的格式");
            tvMobile.requestFocus();
            return false;
        }
        return true;
    }

    /**
     * 设置用户信息
     */
    private void initView(UserInfoEntity.UserBean user) {
        //头像
        if (!TextUtils.isEmpty(user.getAvatar()) && user.getAvatar() != null) {
            String url = ConstantValue.TX_IMG_BASEURL + user.getAvatar();
            ImageLoader.displayImageDefaultHead(this, url, ivAvatar);

        } else {
            ImageLoader.displayImageDefaultHead(context, R.drawable.ic_user_default, ivAvatar);
        }

        //昵称
        tvNick.setText(TextUtils.isEmpty(user.getNick()) ? "小白赚钱" : user.getNick());
        //手机号
        tvMobile.setText(user.getMobile());

        tv_show_id.setText(userid);


        et_name.setText(user.name);

        iidcard.setText(user.idcard);

        tvMobile.setText(user.getMobile());

        String alipayaccountStr=user.alipayaccount;
        if(alipayaccountStr==null||alipayaccountStr.length()==0){
            alipayaccount.setEnabled(true);
        }else
        {
            alipayaccount.setText(alipayaccountStr);
            alipayaccount.setEnabled(false);
        }



    }


    @OnClick({R.id.iv_back, R.id.rl_avatar, R.id.tv_mobile, R.id.tv_user_info})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_avatar:
                //头像
                showOptions();
                break;
            case R.id.tv_user_info:
                //确认修改
                confirm();
                break;
        }
    }



    public static String dateToString(Date data, String formatType) {
        return new SimpleDateFormat(formatType).format(data);
    }


    /**
     * 弹出底部框
     */
    private void showOptions() {
        setImagePicker();
        BottomDialog bottomDialog = BottomDialog.getInstance();
        bottomDialog.show(getSupportFragmentManager(), "takephoto");
        bottomDialog.setClickCallback(new BottomDialog.OnClickCallback() {
            @Override
            public void item1Click() {
                new RxPermissions(MyInfoActivityUpdate.this)
                        .request(Manifest.permission.CAMERA)
                        .subscribe(granted -> {
                            if (granted) {
                                takePhoto();
                            } else {
                                ToastUtils.showShortToastSafe("您拒绝了调用相机拍照");
                            }
                        });
                bottomDialog.dismiss();
            }

            @Override
            public void item2Click() {
                pickImage();
                bottomDialog.dismiss();
            }

            @Override
            public void cancel() {
                bottomDialog.dismiss();
            }
        });
    }

    private void setImagePicker() {
        ImagePicker.getInstance().setSelectLimit(1);
        ImagePicker.getInstance().setCrop(true);
        ImagePicker.getInstance().setMultiMode(false);
        ImagePicker.getInstance().setSaveRectangle(true);
        ImagePicker.getInstance().setFocusHeight(800);
        ImagePicker.getInstance().setFocusWidth(800);
        ImagePicker.getInstance().setOutPutY(800);
        ImagePicker.getInstance().setOutPutX(800);
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        Intent intent = new Intent(context, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
        startActivityForResult(intent, REQUEST_CODE_SELECT);

    }

    /**
     * 相册
     */
    private void pickImage() {
        Intent intent1 = new Intent(context, ImageGridActivity.class);
        startActivityForResult(intent1, REQUEST_CODE_SELECT);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("xuke", "requestCode=" + requestCode);

        switch (requestCode) {
            case REQUEST_CODE_SELECT: {
                try {
                    ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                    String sourcePath = images.get(0).getPath();

                    showProgress();
                    appPresenter.singleuploadfile(new File(sourcePath), ConstantValue.RequestKey.uploadfile);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
        }

        if (requestCode == 100 && resultCode == 200) {
            String s = data.getStringExtra("newName");
            tvNick.setText(s);
        }
    }


    /**
     * 确认提交
     */
    private void confirm() {
        String nick = tvNick.getText().toString().trim();
        String name = et_name.getText().toString().trim();
        String iidcardStr =iidcard.getText().toString().trim();
        String tv_mobileStr=tvMobile.getText().toString().trim();
        String et_codeStr =et_code.getText().toString().trim();
        String alipayaccountStr = alipayaccount.getText().toString().trim();
        showProgress();
        userPresenter.editUserInfo1(userid, nick, name, iidcardStr,alipayaccountStr, tv_mobileStr,et_codeStr,"upload_userinfo");
    }


    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        dismissProgress();
        if (ConstantValue.RequestKey.uploadfile.equals(actionType)) {
            url = (String) data;
            showProgress();
            userPresenter.editUserInfo2(userid, url, "upload_avatar");
        }

        if ("upload_avatar".equals(actionType)) {
            ToastUtils.showShortToastSafe(msg);
            //头像上传成功
            String url2 = ConstantValue.TX_IMG_BASEURL + url;
            ImageLoader.displayImageDefaultHead(this, url2, ivAvatar);
            SPUtils.getInstance().put(ConstantValue.SpType.newavatar, url);

            RxBus.getInstance().post(new RxEvent(RxBusRoute.REFRESH_USER_INFO));
        }

        if ("upload_userinfo".equals(actionType)) {
            ToastUtils.showShortToastSafe(msg);
            SPUtils.getInstance().put(ConstantValue.SpType.nick, tvNick.getText().toString().trim());
            RxBus.getInstance().post(new RxEvent(RxBusRoute.REFRESH_USER_INFO));
        }


    }

    @Override
    public void onFailed(String code, String msg) {
        ToastUtils.showShortToastSafe(msg);
        dismissProgress();
    }
}
